import {ChangeDetectorRef, Component, ElementRef, HostListener, OnInit, ViewChild} from '@angular/core';
import {FormControl, FormGroup, NonNullableFormBuilder, Validators} from "@angular/forms";
import {NzUploadChangeParam, NzUploadFile} from "ng-zorro-antd/upload";
import {HttpService} from "../../service/http/http.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzSafeAny} from "ng-zorro-antd/core/types";
import {UploadFileStatus} from "ng-zorro-antd/upload/interface";
import {NzTableComponent} from "ng-zorro-antd/table";
import {HttpClient, HttpEventType, HttpRequest, HttpResponse} from "@angular/common/http";

const getBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    // @ts-ignore
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
@Component({
  selector: 'app-welcome',
  templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.scss']
})
export class WelcomeComponent implements OnInit {
  fallback = '';

  okLoading  =false;
  listOfData: any[] = [];
  loadingData = false;
  extend:any[] = [];
  shops:any[] = [];
  fileList: NzUploadFile[] = [];
  page = 1;
  size = 10;
  total = 0;
  validateForm!: FormGroup;
  searchForm!: FormGroup;
  data:any;
  showDetails = false;
  uploadFileUrl = "";
  showImageModal = false;
  constructor(private fb: NonNullableFormBuilder,
              private msg:NzMessageService,
              private cdr: ChangeDetectorRef,
              public httpClient:HttpClient,
              private http:HttpService) {
    this.uploadFileUrl = this.http.domain + "/common/uploadFile";
    this.searchForm = this.fb.group({
      wangWangName:[],
      orderNumberId:[],
      gmtCrated:[],
      status:[],
      person:[],
      shopId:[],
      endTime:[],
      userIdList:[],
    });
    this.getAllUser();
  }


  ngOnInit() {

    this.getShops();
    this.getExtend();
  }

  textareaPaste(e:any){
    var files:FileList = e.clipboardData.files;
    this.addImages(files);
    return files.length <= 0;
  }



  async addImages(files:FileList){
    let images:any[] = [];
    for (let i = 0; i < files.length; i++) {
      var file = files[i];
      var name = file.name;
      var array = name.split(".");
      if(array.length > 1){
        var suffix = array[1];
        if(this.isImage(suffix.toLowerCase())){
          const src = await getBase64(file)
          images.push({
            uid:(new Date().getTime()+i)+"",
            name:name,
            file:file,
            thumbUrl:src,
            percent: 0,
            status: 'uploading',
          });
        }
      }
    }
    this.uploadPasteImage(images);
    setTimeout( ()=>{
      this.fileList = this.fileList.concat(images);
      this.cdr.markForCheck();
    },10)
  }

  uploadPasteImage(images:any[]){
    if (images.length <= 0){
      return
    }
    let img = images[0];
    const formData: FormData = new FormData();
    formData.append("file",img.file);
    if (img.uid){
      formData.append("uid",img.uid);
    }
    let  url = this.http.domain + "/common/uploadFile";
    const req = new HttpRequest('POST', url, formData, {
      reportProgress: true,
    });
    this.httpClient.request(req).subscribe((event:any) => {
      if (event.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * event.loaded / event.total);
        this.fileList.forEach(item=>{
          if (item.uid == img.uid){
            item.percent = percentDone;
            return;
          }
        })
      } else if (event instanceof HttpResponse) {

        if (event.status == 200){

          if (event.body.code == 200){
            let res = event.body.data;
            this.fileList.forEach(item=>{
              if (item.uid+"" === res.uid+""){
                item.url = res.url;
                item.status = "done"
                item.percent = 100;
              }
            });
            setTimeout( ()=>{
              this.fileList = [...this.fileList];
              this.cdr.markForCheck();
              images.splice(0,1);
              this.uploadPasteImage(images);
            },50)
          }
        }
      }
    });
  }


  isImage(suffix:string){
    if(suffix === 'jpeg' || suffix === 'jpg' || suffix === 'png' || suffix === 'bmp' || suffix === 'gift'){
      return true;
    }
    return false;
  }

  images:string[] = [];
  showImageModalAction(data:any){
    this.images = data.imgs;
    this.showImageModal = true;
  }
  hideImageModal(){
    this.images= [];
    this.showImageModal = false;
  }

  isUserLoading = false;
  users:any[] = [];

  getAllUser(){
    let url = "/user/getAllUser";
    this.http.get(url, {pageSize:10000,pageNumber:1}).then((res:any)=>{
      this.users = res.records;
    }).catch(err=>{
    });
  }
  loadMoreUser(){

  }

  search(){
    this.page = 1;
    let url = "/order/getList"
    let params:any = JSON.parse(JSON.stringify(this.searchForm.value));
    params.pageNumber = this.page;
    params.pageSize = this.size;
    params.userId = this.http.user.id
    if (params.gmtCrated){
      let date:Date = new Date(params.gmtCrated[0]);
      params.startTime = this.dateFormat(date);
      params.createTime = this.dateFormat(date);
      let date1:Date = new Date(params.gmtCrated[1]);
      params.endTime = this.dateFormat(date1);
      params.gmtCrated = params.startTime;
    }
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === '') {
        delete params[key];
      }
    });
    if (params.userIdList && params.userIdList.length > 0){
      params.userIdList = params.userIdList.join(",");
    }

    this.loadingData = true;
    this.http.get(url,params).then((res:any)=>{
      let records = res.records;
      records.forEach((item:any)=>{
        if (item.extend){
          item.extend = JSON.parse(item.extend);
        }
        item.imgs = [];
        if (item.images && item.images.length > 0){
          item.imgs = item.images.split(",");
        }
      })
      this.listOfData = records;
      this.total = res.total;
      this.loadingData = false;
    }).catch(err=>{
      this.loadingData = false;
      this.msg.warning(err);
    });
  }
  dateFormat(date:Date){
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    let day = date.getDate();
    let H = date.getHours();
    let M = date.getMinutes();
    let s = date.getMilliseconds();
    let y = year + "";
    let m = month + "";
    let d = day + "";

    if (month < 10){
      m = "0"+month;
    }
    if (day < 10){
      d = "0"+day;
    }

    return y+"-"+m+"-"+d + " "+H+":"+M+":00";
  }

  resetSearchForm(): void {
    this.page = 1;
    this.searchForm.reset();
    this.getListData();
  }

  getShops(){
    let url = "/shop/getAll";
    this.http.get(url,{}).then((res:any)=>{
      this.shops = res;
    }).catch(err=>{
    });
  }

  getDisable(data:any){
    return false;
  }

  export(){
    let value = this.searchForm.value;
    let params = "";
    for (const valueKey in value) {
      if (value[valueKey]){
        let v = value[valueKey];
        if (valueKey == 'gmtCrated'){
          let date:Date = new Date(v);
          params += "&"+valueKey+"="+this.dateFormat(date);
        }else {
          params += "&"+valueKey+"="+v;
        }
      }
    }

    let url = this.http.domain + `/order/export?pageNumber=${this.page}&pageSize=${this.size}&userId=${this.http.user.id}` + params;
    console.log(url);
    window.location.href = url;
  }

  getListData(){

    let url = "/order/getList"
    let params = {
      pageNumber:this.page,
      pageSize:this.size,
      userId:this.http.user.id
    }

    this.loadingData = true;
    this.http.get(url,params).then((res:any)=>{
      let records = res.records;
      records.forEach((item:any)=>{
        item.imgs = [];
        if (item.images && item.images.length > 0){
          item.imgs = item.images.split(",");
        }
        if (item.extend){
          item.extend = JSON.parse(item.extend);
        }
      })
      this.listOfData = records;
      this.total = res.total;
      this.loadingData = false;
    }).catch(err=>{
      this.msg.warning(err);
    });
  }
  changePage(p:any){
    this.page = p;
    this.getListData();
  }

  handlePayCancel(){
    this.showDetails = false;
  }
  handlePay(){
    window.open("https://www.alipay.com/");
    this.showDetails = false;
  }

  pay(data:any){
    this.data = data;
    this.showDetails = true;
  }

  hideDetail(){
    this.showDetails = false;
  }

  //审核状态;0-未审核；1-已审核；2-付款失败；3-付款成功
  getStatus(status:number){
    if (status == 0){
      return "待审核"
    }else if (status == 1){
      return "待付款"
    }else if (status == 2){
      return "付款失败"
    }else if (status == 3){
      return "付款成功"
    }
    return "已取消";
  }

  getStatusColor(status:number){
    if (status == 0){
      return "warning"
    }else if (status == 1){
      return "processing"
    }else if (status == 2){
      return "error"
    }else if (status == 3){
      return "success"
    }
    return "default";
  }

  getExtendValue(item:any,value:any){
    if (value.extend){
      let a = value.extend[item.id+""];
      return a ? a : "-";
    }
    return "-";
  }

  getExtend(){
    let url = "/config/getAll"
    this.http.get(url,{}).then((res:any)=>{

      let obj:any = {
        id:[''],
        shopId:['', [Validators.required]],
        wangWangName: ['', [Validators.required]],
        orderNumberId: ['', [Validators.required]],
        imgs: [''],
        name: ['', [Validators.required]],
        alipay: ['', [Validators.required]],
        money: new FormControl({value: '', disabled: true}, Validators.required),
        person: ['', [Validators.required]],
      }
      let a:any[] = [];
      res.forEach((item:any)=>{
        if (item.isShow == 1){
          obj[item.id+""] = [''];
          a.push(item);
        }
      })
      this.extend = a;
      this.validateForm = this.fb.group(obj);
      this.getListData();
    })
  }

  previewImage: string | undefined = '';
  previewVisible = false;

  handlePreview = async (file: NzUploadFile): Promise<void> => {

  };

  examineData(data:any){

    let url = "/order/examineData";
    let params = {
      id:data.id
    }
    this.http.get(url,params).then(res=>{
      this.msg.success("审核成功");
      this.getListData();
    }).catch(err=>{
      this.msg.error(err);
    })
  }

  isVisible = false;
  add(){
    this.fileList = [];
    this.isVisible = true;
    this.validateForm.reset();
  }

  isEdit = false;
  edit(data:any){
    this.isEdit = true;
    let obj:any = {
      id:data.id,
      shopId:data.shopId,
      wangWangName: data.wangWangName,
      orderNumberId: data.orderNumberId,
      imgs: [''],
      name: data.name,
      alipay: data.alipay,
      money: data.money,
      person: data.person,
    }
    this.fileList = [];
    let imgs:string[]=[];
    if (data.images.length > 0){
      imgs = data.images.split(',');
    }

    imgs.forEach((item,index)=>{
      this.fileList.push({
        uid:(new Date().getTime()+index)+"",
        name:index+"",
        url:item,
        status:'done'
      })
    });


    if (data.extend){
      this.extend.forEach((item:any)=>{
        if (item.isShow == 1){
          obj[item.id+""] = data.extend[item.id+""];
        }
      })
    }
    this.validateForm.reset(obj);
    this.isVisible = true;
  }

  handleCancel(){
    this.isVisible = false;
  }

  deletedOrder(item:any){

    let url = "/order/deleteList"
    let params = [item.id];
    this.http.postBody(url,params).then(res=>{
      this.getListData();
      this.msg.success("删除成功");
    }).catch(err=>{
      this.msg.success(err);
      console.log(err);
    });

  }

  changeShop(value:any){
    this.shops.forEach((item:any)=>{
      if (value == item.id){
        this.validateForm.controls['money'].setValue(item.payMoney);
        return;
      }
    })
  }

  handleOk(){
    let imgs:string[] = [];
    this.fileList.forEach(item=>{
      if (item.status == 'done'){
        if (item.response && item.response.code == 200){
          imgs.push(item.response.data.url);
        }else {
          imgs.push(item.url!);
        }
      }
    });
    console.log(this.fileList);
    console.log(imgs);
    if (this.validateForm.valid) {

      let value:any = this.validateForm.value;
      let obj:any = {};
      this.extend.forEach(item=>{
        obj[item.id+''] = value[item.id];
        delete value[item.id];
      });
      value.userId = this.http.user.id;
      value.extend = JSON.stringify(obj);
      value.images = imgs.join(",");
      let url = "/order/add"
      if (this.isEdit){
        url = "/order/update";
      }
      this.okLoading = true;
      this.http.postBody(url,value).then(res=>{
        this.okLoading = false;
        this.isVisible = false;
        this.msg.success(this.isEdit ? "修改成功" : "添加成功");
        if (!this.isEdit){
          this.page = 1;
        }
        this.getListData();
      }).catch(err=>{
        this.okLoading = false;
        this.msg.error(err);
      });
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
}
